#include"my.h"
//服务器
sqlite3* db;    //数据库全局变量

void insert_history_table(char* word,char* username)
{
	//获得时间
	time_t t;
	char sql[512] = {0};
	sprintf(sql,"insert into history_info values('%s','%s','%s');",username,word,ctime(&t));
	sqlite3_exec(db,sql,NULL,NULL,NULL);
}
void deal_history_word(int new_sockfd,char* username)
{
	MSG msg = {0};
	//从数据库中查找
	//插入
	//发出
	char sql[512] = {0};
	sprintf(sql,"select * from history_info where username = '%s';",username);
	char **reseltp;
	int row;
	int column;

	sqlite3_get_table(db,sql,&reseltp,&row,&column,NULL);
	
	if(row == 0)//没查
	{
		msg.type = 0;//表示查询完毕
		send(new_sockfd,&msg,sizeof(MSG),0);
		return;
	}
	//有数据
	int i = 0;
	for(i;i<row;i++)
	{
		msg.type = 4;
		strcpy(msg.name,reseltp[3*i+4]);
		strcpy(msg.data,reseltp[3*i+5]);
		send(new_sockfd,&msg,sizeof(MSG),0);
	}
	msg.type = 0;
	send(new_sockfd,&msg,sizeof(MSG),0);

}

void deal_find_sys(int new_sockfd,MSG * msg,char* username)
{
	
	FILE * fd = fopen("./dict.txt","r");
	if(fd == NULL)
	{
		perror("fopen ");
		exit(-1);
	}
//	char buf[100] = {0};
	//不断从字典中查询
	int n = strlen(msg->name);
	while(fgets(msg->data,sizeof(msg->data),fd)!= NULL)
	{
		//比较 查到的内容 和 输入的内容+空格，确保比较字典中的内容是结束的
		if(strncmp(msg->data,strcat(msg->name," "),n+1)==0)
		{
			msg->type = 1;
			send(new_sockfd,msg,sizeof(MSG),0);
			//s我已经查询到了，插入数据库
			insert_history_table(msg->name,username);//需要参数吗？单词，把单词给我，数据库(全局)
			return ;
		}
	}
	// 跳出了while循环还是没有结果啊
	msg->type = -1;
	send(new_sockfd,msg,sizeof(MSG),0);

}
void deal_login_sys(int new_sockfd,MSG* msg,char *username)
{
	//查询数据库中有没有这条用户数据
	char sql[512]= {0};
	printf("账号--->%s\n",msg->name);
	printf("密码--->%s\n",msg->data);
	sprintf(sql,"select * from user_info where username = '%s' and password = '%s';",msg->name,msg->data);
	int ret;
	int row;
	int column;
	char ** reseltp;
	char * errmsg;
	ret = sqlite3_get_table(db,sql,&reseltp,&row,&column,&errmsg);
	if(ret < 0)
	{
		printf("%s\n",errmsg);
		//return;----->???
	}
	if(row==1)
	{
		msg->type = 0;//0代表普遍成功
		strcpy(username,msg->name);
		send(new_sockfd,msg,sizeof(MSG),0);
	}
	else
	{
		msg->type = -1;//
		send(new_sockfd,msg,sizeof(MSG),0);
	}

}
//数据库初始化（）
void sqlite_init()
{
	int ret = sqlite3_open("./dict.db",&db);
	if(ret<0)
	{
		//如果没表，直接退出
		perror("sqlite3_open ");
		exit(-1);
	}
	char sql1[256] = "create table if not exists user_info(username varchar(50),password varchar(100));";
	char *errmsg = NULL;
	ret = sqlite3_exec(db,sql1,NULL,NULL,&errmsg);
	if(ret < 0)//执行出问题
	{
		printf("%s\n",errmsg);
		exit(-1);
	}
	char sql2[256] = "create table if not exists history_info(username varchar(50),word varchar(50),time varchar(100));";
	ret = sqlite3_exec(db,sql2,NULL,NULL,&errmsg);
	if(ret<0)
	{
		printf("%s\n",errmsg);
		exit(-1);
	}
	printf("俩表正常\n");

}
void deal_register_sys(int new_sockfd,MSG*msg)
{
	//按道理注册需要使用数据库，并且后面如登录检测也需数据库
	//故定义一个数据库全局变量
	//和定义一个数据库初始化函数
	char sql[512]={0};
	sprintf(sql,"select * from user_info where username = '%s';",msg->name);
	int row = 0;//行？
	int column = 0;
	char * errmsg = NULL;
	char** reseltp = NULL;//二维数组取到的结果(好像用不到？)
	int ret = sqlite3_get_table(db,sql,&reseltp,&row,&column,&errmsg);
	if(ret < 0)//执行本身出现问题
	{
		printf("%s\n",errmsg);
		return;
	}
	if(row > 0)//如果数据中有相同的用户名
	{
		msg->type = -1;
		send(new_sockfd,msg,sizeof(MSG),0);//?
		return;
	}
	else  //不重名，可以注册
	{
		memset(sql,0,sizeof(sql));
		sprintf(sql,"insert into user_info values('%s','%s');",msg->name,msg->data);
		ret = sqlite3_exec(db,sql,NULL,NULL,&errmsg);
		if(ret<0)//语句有问题
		{
			printf("errmsg");
			return;
		}
		//成功
		msg->type = 0;  //－１是失败
		send(new_sockfd,msg,sizeof(MSG),0);
		return;
	}

}
//线程的执行函数(把new_sockfd传进去)
void* do_client(void* arg)
{
	//(多线程服务器)客户端与do_client一一对应
	//做查询历史记录
	//username作为参数传递给登录函数，如果函数登录成功，赋值，否则为空
	char username[100] = {0};
	int new_sockfd = *((int*)arg);
	MSG msg = {0};
	while(1)
	{
		int ret = recv(new_sockfd,&msg,sizeof(MSG),0);
		if(ret<=0)
		{
			printf("%d:客户端断开连接\n",new_sockfd);
			close(new_sockfd);
			pthread_exit(NULL);
		}
		else //正常
		{
			if(msg.type == 1) //注册
			{
				deal_register_sys(new_sockfd,&msg);//msg注册用的账号密码
			}
			else if(msg.type == 2)
			{
				//参数用于通信，传递用户名和密码
				deal_login_sys(new_sockfd,&msg,username);
			}
			else if(msg.type == 3)
			{
				deal_find_sys(new_sockfd,&msg,username);
			}
			else if(msg.type == 4)
			{
				//查询用不到msg信息
				deal_history_word(new_sockfd,username);
			}
		}
	}
}
int main(int argc, const char *argv[])
{
	//初始化数据库
	sqlite_init();
	//tcp
	//(1)socket():创建套接字
	int sockfd = socket(AF_INET,SOCK_STREAM,0);
	if(sockfd == -1)
	{
		perror("socket failed\n");
		exit(-1);
	}

	struct sockaddr_in server_addr = {0};
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(7788);
	server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    //(2)bind():绑定本机的ip地址和端口号
	int ret = bind(sockfd,(struct sockaddr*)&server_addr,sizeof(server_addr));
	if(ret==-1)
	{
		perror("bind ");
		exit(-1);
	}
	//(3)listen():监听
	listen(sockfd,5);
	//(4)阻塞等待连接：accept()
    while(1)
	{
		int new_sockfd = accept(sockfd,NULL,NULL);
		printf("有新的客户端连接%d\n",new_sockfd);
		pthread_t tid;
		pthread_create(&tid,NULL,do_client,&new_sockfd);
	}

	return 0;
}
